package cn.ckx.coding.common.resolver;


import cn.ckx.coding.common.annotation.login.LoginUser;
import cn.ckx.coding.properties.AppProperties;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


/**
 * 有@LoginUser注解的方法参数，注入当前登录用户,必须为登录状态
 *
 * @author kunxin.cai
 */
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    
    private final AppProperties appProperties;
    
    public LoginUserHandlerMethodArgumentResolver(AppProperties appProperties) {
        this.appProperties = appProperties;    
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //parameter.getParameterType().isAssignableFrom(UserEntity.class) &&
        return  parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //获取用户ID
        Object object = request.getAttribute(appProperties.getLogin().getUserId(), RequestAttributes.SCOPE_REQUEST);
        if(object == null){
            return null;
        }
        //todo 获取用户信息 UserEntity user = userService.getById((Long)object);
        
        return new Object();
    }
}
